const axios = require('axios')
const cheerio = require('cheerio')
const iconv = require('iconv-lite')

module.exports = async(ctx, next) => {
    var url = ctx.query.url
    var list = await new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: url,
            responseType: 'stream'
        }).then(res => {
            var stream = []
            res.data.on('data', st => {
                stream.push(st)
            })
            res.data.on('end', () => {
                var buffer = Buffer.concat(stream)
                let domStr = iconv.decode(buffer, 'utf8')
                var $ = cheerio.load(domStr)
                var chapterList = []
                $('#list dd').each(function() {
                    var chapter = {}
                    chapter.chapterUrl = $(this).find('a').attr('href')
                    chapter.chapterName = $(this).text()
                    chapterList.push(chapter)
                })
                resolve(chapterList)
            })
        })
    })
    ctx.body = list

}